<template>
  <vol-edit
    ref="edit"
    :keyField="options.key"
    :tableName="options.tableName"
    :tableCNName="options.tableCNName"
    :labelWidth="100"
    :formFields="options.editFormFields"
    :formOptions="options.editFormOptions"
    :detail="options.detail"
    @initButtons="initButtons"
    :updateBefore="updateBefore"
    :editPageAddAfter="editPageAddAfter"
    :addBefore="addBefore"
    :addAfter="addAfter"
    :loadFormAfter="loadFormAfter"
    @initDetailButtons="initDetailButtons"
  >
    <template #content v-if="curId">
      <div style="padding: 0px 20px 20px; background-color: #fff; width: 100%">
        <el-form style="width: 100%">
          <div style="font-size: 14px; margin-bottom: 4px">标签设计</div>
          <el-form-item>
            <el-button type="primary" @click="labelDesign(curId)"> 标签设计</el-button>
          </el-form-item>
          <div style="font-size: 14px; margin-bottom: 4px">标签字段</div>
          <el-form-item>
            <!-- v-show="!fieldDetail.length" -->
            <!-- <el-button style="margin-left: 3px" type="primary" @click="addDetail()" size="mini" circle> 新增
                        </el-button> -->
            <el-row
              :gutter="15"
              v-for="(d, i) in fieldDetail"
              :key="i"
              style="margin: 0; margin-bottom: 10px; width: 100%"
            >
              <el-col :span="6">
                <el-select
                  v-model="d.LabelConfigDetailName"
                  @change="getViewField"
                  :disabled="!!$route.query.isSee"
                  placeholder="视图名称"
                  style="width: 100%"
                >
                  <el-option
                    v-for="i in viewOptions"
                    :key="i.BarcodeElementId"
                    :label="`${i.CodingParam} ${i.CodingDesc}`"
                    :value="i.CodingParam"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="15">
                <el-select
                  v-model="d.LabelConfigDetailValue"
                  :disabled="!!$route.query.isSee"
                  placeholder="不可为空值的字段"
                  class="mb-5"
                  style="width: 100%"
                  multiple
                  filterable
                >
                  <el-option v-for="i in viewFiledOptions" :key="i" :label="i" :value="i"></el-option>
                </el-select>
                <el-select
                  v-model="d.AllowNullValue"
                  :disabled="!!$route.query.isSee"
                  placeholder="可为空值的字段"
                  style="width: 100%"
                  multiple
                  filterable
                >
                  <el-option v-for="i in viewFiledOptions" :key="i" :label="i" :value="i"></el-option>
                </el-select>
              </el-col>
              <el-col :span="3" style="display: flex" v-if="!$route.query.isSee">
                <el-button type="danger" size="small" :icon="Delete" @click="removeDetail(i)" circle> </el-button>
                <el-button
                  style="margin-left: 3px"
                  type="primary"
                  @click="addDetail(i)"
                  size="small"
                  :icon="Plus"
                  circle
                ></el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </vol-edit>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="design-dialog"
    title="标签设计"
    v-model="designVisible"
    width="80%"
  >
    <iframe :src="designUrl" width="100%" scrolling="auto" style="min-height: 550px"></iframe>
  </el-dialog>
</template>

<script setup></script>

<script>
import { defineComponent, ref, reactive, getCurrentInstance, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import store from '@/store/index'
import http from '@/api/http.js'
import editOptions from './options.js'
import _ from 'lodash'
import { Delete, Plus } from '@element-plus/icons-vue'

//参数传递与方法实现，看VolEdit.vue文件
export default defineComponent({
  setup(props, context) {
    //vol-edit组件
    const { proxy } = getCurrentInstance()

    const edit = ref(null)
    const fieldDetail = reactive([{}])
    const route = useRoute()
    const options = reactive({
      //表单字段
      editFormFields: {},
      //表单配置
      editFormOptions: [],
      //明细表信息
      detail: {
        cnName: '',
        table: '',
        url: '',
        columns: [],
        sortName: '',
        key: '',
      },
      details: [],
    })
    Object.assign(options, editOptions())
    const curId = computed(() => {
      return options.editFormFields.LabelId ?? route.query.id
    })

    //初始化主表按钮
    const initButtons = (buttons) => {}
    //初始化明细表按钮
    const initDetailButtons = (buttons) => {}
    const editPageAddAfter = (x) => {
      options.editFormFields = { ...options.editFormFields, ...x.data }
      return false
    }
    // 暂时移除通用字段
    options.editFormFields.IsCommon = 1

    options.editFormOptions.flat().forEach((i) => {
      i.readonly = !!route.query.isSee
    })
    const loadFormAfter = (params) => {
      proxy.http.get(proxy.$api.label + 'GetLabelConfigDetail', { LabelId: params.rows[0].LabelId }).then((r) => {
        if (r.length) {
          fieldDetail.length = 0
          r.forEach((i) => {
            proxy.getViewField(i.LabelConfigDetailName)
            // 对于每个 i，创建一个新的对象并将其 push 到 fieldDetail 中
            fieldDetail.push({
              LabelConfigDetailName: i.LabelConfigDetailName,
              LabelConfigDetailValue: i.LabelConfigDetailValue.split(','),
              AllowNullValue: i.AllowNullValue.split(','),
            })
          })
        } else {
        }
      })
      return true
    }
    return { fieldDetail, curId, edit, options, loadFormAfter, initButtons, initDetailButtons, editPageAddAfter }
  },
  /****************************************/
  //这里是vue2语法,不想写vue3语法就在这里写vue2
  data() {
    return {
      designUrl: null,
      designVisible: false,
      Delete: Delete,
      Plus: Plus,
      data: {},
      designBaseUrl: '/labelDesign/index.html',
      viewOptions: [],
      viewFiledOptions: [],
    }
  },
  methods: {
    hasIntersection(arr1, arr2) {
      const set = new Set(arr1)
      for (const item of arr2) {
        if (set.has(item)) {
          return true // 找到交集
        }
      }
      return false // 无交集
    },
    checkIsArr(arr) {
      arr.forEach((i) => {
        i.isFlag = this.hasIntersection(i.LabelConfigDetailValue, i.AllowNullValue)
      })
    },
    addBefore(form) {
      // 如果有id就不用这个默认的新增接口了
      if (this.$route.query.id) {
        this.updateBefore()
        return false
      } else {
        return true
      }
    },
    addAfter(params) {
      this.$router.replace(this.$route.path + `?id=${params.data.LabelId}`)
      return true
    },
    updateBefore() {
      this.checkIsArr(this.fieldDetail)
      if (this.fieldDetail.some((i) => i.isFlag)) {
        this.$message.error('不能同时可为空和不可为空！')
        return
      }
      let list = _.cloneDeep(this.fieldDetail)
      list.forEach((i) => {
        i.LabelConfigDetailValue = i.LabelConfigDetailValue.join()
        i.AllowNullValue = i.AllowNullValue.join()
      })
      let data = {
        ...this.options.editFormFields,
        DetailList: list,
        LabelId: Number(this.curId),
      }
      this.http.post(this.$api.label + 'ModifyLabelDesign', data).then((r) => {
        this.$message.success('修改成功')
      })
      return false
    },
    labelDesign(id) {
      this.designUrl = `${this.designBaseUrl}?id=${id}&api=${this.$api.label}&width=${this.options.editFormFields.WidthSize}&height=${this.options.editFormFields.HeightSize}`
      this.designVisible = true
    },
    addDetail(i) {
      i = i || 0
      this.fieldDetail.splice(i + 1, 0, {})
    },

    removeDetail(i) {
      if (this.fieldDetail.length == 1) return
      this.fieldDetail.splice(i, 1)
    },
    getView() {
      console.log(this.$route.path, 'this.$route.path')
      this.http
        .post(this.$api.barcodeElement + 'getPageData', {
          rows: 9999,
          wheres: JSON.stringify([
            {
              name: 'CodingType',
              value: 'View',
            },
          ]),
        })
        .then((r) => {
          this.viewOptions = r.rows
        })
    },
    getViewField(v) {
      this.http
        .get(this.$api.label + 'GetViewField', {
          ViewName: v,
        })
        .then((r) => {
          this.viewFiledOptions = r
        })
    },
  },

  created() {
    //this.options
  },
  mounted() {
    this.getView()
  },
})
</script>
